<?php
namespace app\common\controller;
trait Uploads{
	private $media='media';// 媒体路径存贮表
	private $member='member';// 媒体路径存贮表

	// 上传头像文件
	function loadHeadImg($file,$validate=['ext'=>'jpg,png,gif,jpeg']){
	    $info=$file->validate($validate)->move('uploads');
	    if($info){
	    	return success('/'.$info->getSaveName());
	    }else{
	    	return error($file->getError());
	    }
	}
	// 上传身份证证件照
	function loadIdNumsImg($file,$fileName,$idNums='idnums',$validate=['ext'=>'jpg,png,gif,jpeg']){
	    $info=$file->validate($validate)->move($idNums,$fileName);
	    if($info){
	    	return success('/'.$info->getSaveName());
	    }else{
	    	return error($file->getError());
	    }
	}
	/**
	 * 文件上传 （当前仅实现服务器上传）
	 * @param  SplFileObject $file 
	 * @return array
	 */
	function uploads($file,$_inputname='file',$validate=['ext'=>'jpg,jpeg,png,gif,mp4,mp3,avi,mov,mpg,mpeg,ram,aiff,ogg,wav,midi,rm,ape,aac']){
		$rs=[];
		$err='';
		if(is_array($_FILES[$_inputname]['name'])){ //多文件上传
			foreach ($file as $k => $v) {
				$typeArr=explode('/', $v->getInfo()['type']);
				$type=0;
				switch ($typeArr[0]) {
					case 'audio':
						$type=3;
						break;
					case 'image':
						$type=1;
						break;
					case 'video':
						$type=2;
						break;
				}
				$info=$v->validate($validate)->move('uploads');
				if($info){
					$ext=$info->getExtension();
					$rs[$k]=[
						'link'=>'/'.$info->getSaveName(),
						'ext'=>'.'.$ext,
						'type'=>$type,
					];
				}else{
					$err.=$v->getError().'、';
				}
				if(!empty($rs)){
					if ($rs[$k]['type'] == 1) {
						$this->image_png_size_add(env('root_path').'public/uploads'.$rs[$k]['link'],env('root_path').'public/uploads'.$rs[$k]['link']);
					}
				    if ($rs[$k]['ext'] == '.jpg' && $rs[$k]['type'] == 1){
				        //把一幅图像brophp.jpg旋转180度
				        $this->rotate(env('root_path').'public/uploads'.$rs[$k]['link'], 360);
				    }
			    }
			}
		}else{
			$typeArr=explode('/', $file->getInfo()['type']);
			$type=0;
			switch ($typeArr[0]) {
				case 'audio':
					$type=3;
					break;
				case 'image':
					$type=1;
					break;
				case 'video':
					$type=2;
					break;
			}
			$info=$file->validate($validate)->move('uploads');
			if($info){
				$rs=[
					'link'=>'/'.$info->getSaveName(),
					'ext'=>'.'.$info->getExtension(),
					'type'=>$type,
				];
			}else{
				$err=$file->getError();
			}
			if(!empty($rs)){
				if ($rs['type'] == 1) {
					 $this->image_png_size_add(env('root_path').'public/uploads'.$rs['link'],env('root_path').'public/uploads'.$rs['link']);
				}
				if ($rs['ext'] == '.jpg' && $rs['type'] == 1){
				    //把一幅图像brophp.jpg旋转180度
				    $this->rotate(env('root_path').'public/uploads'.$rs['link'], 360);
				}
			}
		}
		if(empty($rs))return $err;
		$result=model($this->media)->add($rs);
		$result=$result->toArray();
		
		if(is_integer(key($result))){
			foreach ($result as $k => $v) {
				if($v['type']==3){
					$result[$k]['link']=_static().'/images/audio.png';
					$result[$k]['src']=_static().'/images/audio.png';
				}else{
					$result[$k]['src']=images($result[$k]['link']);
				}
			}
		}else{
			if($result['type']==3){
				$result['link']=request()->domain().'/static/images/audio.png';
				$result['src']=request()->domain().'/static/images/audio.png';
			}else{
				$result['src']=images($result['link']);
			}
		}
		return $result;
	}
	
    //用给定角度旋转图像，以jpeg图像格式为例
    protected function rotate($filename,$degrees){
        //创建图像资源，以jpeg格式为例
        $source =imagecreatefromjpeg($filename);
        //使用imagerotate()函数按指定的角度旋转
        $rotate = imagerotate($source,$degrees, 0);
        //旋转后的图片保存
        imagejpeg($rotate,$filename);
    }


	/**
	 * 文件上传 （当前仅实现服务器上传）
	 * @param  SplFileObject $file 
	 * @param  用户可上传的文件类型 $validate 
	 * @param  上传成功后保存的表 $tb 
	 * @param  用户id $uid 
	 * @return array
	 */
	function huploads($file,$validate=['ext'=>'jpg,png,gif'],$tb,$uid){
		$rs=[];
		$err='';

		// 验证文件类型
		$typeArr=explode('/', $file->getInfo()['type']);

		// 保存文件
		$info=$file->validate($validate)->move('uploads');
		if($info){
			$rs=[
				'head_img'=>'/'.$info->getSaveName(),
				// 'id'=>$uid,
				// 'type'=>$type,
			];
		}else{
			$err=$file->getError();
		}

		if(empty($rs))return $err;
		$this->image_png_size_add(env('root_path').'public/uploads'.$rs['head_img'],env('root_path').'public/uploads'.$rs['head_img']);
		$result=model($this->member)->save($rs,['id'=>$uid]);
		// 判断购物车更新是否成功
		if ($result > 0) {
			$result = $rs;
		}
		else{
			$result = '';
		}
		return $result;
	}
    function base64Uploads($base64_img){
    	//存放在当前目录的upload文件夹下
    	$up_dir=env('root_path').'public/uploads';
    	$up_dir2=$up_dir.'/'.date('Ymd').'/';
    	if(!file_exists($up_dir2)){
    	    mkdir($up_dir2,0777);
    	}
    	if(preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_img, $result)){
    	    $type = $result[2];
    	    if(in_array($type,array('pjpeg','jpeg','jpg','gif','bmp','png'))){
    	    	$filename='/'.date('Ymd').'/'.md5(date('YmdHis').$type.rand(0,9999)).'.'.$type;
    	        $new_file = $up_dir.$filename;
    	        if(file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_img)))){
    	            $rs=[
    	            	'link'=>$filename,
    	            	'type'=>1,
    	            	'ext'=>'.'.$type,
    	            ];
    	            return $this->saveImages($rs);
    	        }else{
    	            return error('图片上传失败');
    	        }
    	    }else{
    	        return error('图片上传类型错误');
    	    }

    	}else{
    	    //文件错误
    	    return error('文件错误');
    	}
    }
    private function saveImages($rs){
    	$result=model($this->media)->add($rs);
    	$result=$result->toArray();
    	$result['src']=request()->domain().'/uploads'.$result['link'];
    	return success('上传成功',0,$result);
    }
	// 删除上传的文件
	function delMedia($id=0,$where=[]){
		if($id>0||is_array($id)&&!empty($id)||count($where)){
			if(empty($where)){
				if(is_array($id)){
					$where=['id'=>['id','in',$id]];
				}else{
					$where=['id'=>$id];
				}
			}
			$has=model('media')->readAll($where,0,['field'=>'id,link']);
			if(empty($has)){
				return json(lang('Data does not exist'),1);
			}
			$del=model('media')->del($where);
			if(!$del){
				return json(lang('Failed operation'),1);
			}
			foreach ($has as $v) {
				$file=env('root_path').'public/uploads/'.$v['link'];
		        if(is_file($file)){
		            unlink($file);
		        }
			}
			return json(lang('Successful operation'));
		}
	}

	/** 
	* desription 压缩图片 
	* @param sting $imgsrc 图片路径 
	* @param string $imgdst 压缩后保存路径 
	*/
	function image_png_size_add($imgsrc,$imgdst){  
		// 获取图像尺寸，类型等信息。
		list($width,$height,$type)=getimagesize($imgsrc);  
		// echo "$width";
		// 设置图片宽高
		$new_width = $width>720?720:$width;
		if ($new_width == 720) {
			$new_height = (720/$width)*$height;
		}
		else{
			$new_height = $height;
		}
		// $new_height =($height>720?720:$height)*0.9;  
		switch($type){  
			case 1:  
			   	$giftype = $this->check_gifcartoon($imgsrc);  
			   	if($giftype){  
				    header('Content-Type:image/gif');
				    // 新建图片，宽高为：$new_width * $new_height
				    $image_wp=imagecreatetruecolor($new_width, $new_height);
				    // 打开获取图片信息
				    $image = imagecreatefromgif($imgsrc);
				    // 重采样拷贝部分图像并调整大小
				    // imagecopyresampled() 将一幅图像中的一块正方形区域拷贝到另一个图像中，平滑地插入像素值，因此，尤其是，减小了图像的大小而仍然保持了极大的清晰度。
				    imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);  
				    imagejpeg($image_wp, $imgdst,75);  
				    imagedestroy($image_wp);  
			   	}  
			   	break;  
			case 2:  
			   	header('Content-Type:image/jpeg');  
			   	$image_wp=imagecreatetruecolor($new_width, $new_height);  
			   	$image = imagecreatefromjpeg($imgsrc);  
			   	imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);  
			   	imagejpeg($image_wp, $imgdst,75);  
			   	imagedestroy($image_wp);  
			   	break;  
			case 3:  
			   	header('Content-Type:image/png');  
			   	$image_wp=imagecreatetruecolor($new_width, $new_height);  
			   	$image = imagecreatefrompng($imgsrc);  
			   	imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);  
			   	imagejpeg($image_wp, $imgdst,75);  
			   	imagedestroy($image_wp);  
			   	break;  
		}  
	}

	/** 
	* desription 判断是否gif动画 
	* @param sting $image_file图片路径 
	* @return boolean t 是 f 否 
	*/
	function check_gifcartoon($image_file){  
	 	$fp = fopen($image_file,'rb');  
	 	$image_head = fread($fp,1024);  
	 	fclose($fp);  
	 	return preg_match("/".chr(0x21).chr(0xff).chr(0x0b).'NETSCAPE2.0'."/",$image_head)?false:true;  
	}

	/**
	 * 删除上传的文件
	 * @param  string $file 例：/20180929/05464413546.png
	 * @return void
	 */
	function deleteUploadFile($file=null){
		if(is_null($file)){
			return ;
		}
		$file=env('root_path').'public/uploads/'.$file;
		if(is_file($file)){
		    unlink($file);
		}
	}
}
